<template>
	<view class="container">
		<view>
			<view style="margin: 20rpx;">
				设置用户
			</view>
			<uni-forms ref="form" :modelValue="formData" :rules="rules">
				<uni-forms-item label="用户名" name="username" required>
					<input type="text" v-model="formData.username" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="账号" name="account" required>
					<input type="text" v-model="formData.account" placeholder="请输入账号" />
				</uni-forms-item>
				<uni-forms-item label="密码" name="password" required>
					<input type="password" v-model="formData.password" placeholder="请输入密码" />
				</uni-forms-item>
				<uni-forms-item label="邮箱" name="email" required>
					<input class="input" v-model="formData.email" type="text" placeholder="请输入邮箱"/>
				</uni-forms-item>
			</uni-forms>
			<view style="width: 300rpx; margin: 0 auto;">
				<button class="uni-button" type="primary" @click="submit">提交</button>
			</view>
			
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import {onShow,onLoad} from '@dcloudio/uni-app'
import {baseUrl,checkLogin,handleRequestCode} from '../../static/js/common.js'

	let auth=null

	function submit(){
		uni.request({
			url:baseUrl+'/user/register',
			method:'POST',
			data:formData.value,
			success:(res)=>{
				handleRequestCode(res.data)
				if(res.data.code==200){
					uni.showToast({
						icon:'success',
						title:'操作成功'
					})
					setTimeout(() => {
						uni.navigateTo({
							url:'/pages/adminIndex/adminIndex'
						})
					}, 1000)
				}
			}
		})
	}
	
	let formData= ref({
					account:'',
					password:'',
					username: '',
					email: '',
					id:'',
					auth:2
				})
				
	let rules={
		name:{
			rules: [{
					required: true,
					errorMessage: '请输入姓名',
				}
			]
		},
		// 对email字段进行必填验证
		email: {
			rules: [{
				format: 'email',
				errorMessage: '请输入正确的邮箱地址',
			}]
		}
	}
	
	function fillData(id){
		uni.request({
			url:baseUrl+'/user/detail',
			header:{'Authorization':auth},
			data:{'id':id},
			success:(res)=>{
				formData.value.username=res.data.data.username
				formData.value.account=res.data.data.account
				formData.value.password=res.data.data.password
				formData.value.email=res.data.data.email
			}
		})
	}
	
	onLoad((option)=>{
		auth=localStorage.getItem('Authorization')
		if(option.userId!=null){
			formData.value.id=option.userId
			fillData(option.userId)
		}
	})
	onShow(()=>{
		auth=checkLogin()
	})
</script>

<style lang="scss" scoped>
	.container{
		border: 1px solid #ddd;
		padding: 50rpx;
		width: max-content;
		margin: 0 auto;
	}
	input{
		padding-top: 15rpx;
	}
</style>